// ** React Imports
import { Fragment, useState, forwardRef } from 'react'
// ** Table Data & Columns
import { data, columns } from './data'

// ** Third Party Components
import ReactPaginate from 'react-paginate'
import DataTable from 'react-data-table-component'
import { ChevronDown, User } from 'react-feather'
import Select from 'react-select'

// ** Reactstrap Imports
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  CardTitle,
  CardHeader,
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Label,
} from 'reactstrap'

// ** Bootstrap Checkbox Component
const BootstrapCheckbox = forwardRef((props, ref) => (
  <div className="form-check">
    <Input type="checkbox" ref={ref} {...props} />
  </div>
))

const DataTableWithButtons = () => {
  // ** States
  const [currentPage, setCurrentPage] = useState(0)
  const [searchValue, setSearchValue] = useState('')
  const [filteredData, setFilteredData] = useState([])
  const [modalShow, setModalShow] = useState(false)
  const mockOptions = [
    { value: '1', label: '一级管理' },
    { value: '2', label: '二级管理' },
    { value: '3', label: '普通用户' },
  ]
  // ** Function to handle Modal toggle
  const handleModalShow = () => setModalShow(!modalShow)

  // ** Function to handle filter
  const handleFilter = (e) => {
    const value = e.target.value
    let updatedData = []
    setSearchValue(value)

    const status = {
      1: { title: 'Current', color: 'light-primary' },
      2: { title: 'Professional', color: 'light-success' },
      3: { title: 'Rejected', color: 'light-danger' },
      4: { title: 'Resigned', color: 'light-warning' },
      5: { title: 'Applied', color: 'light-info' },
    }

    if (value.length) {
      console.log('data', data)
      console.log('value', value)
      updatedData = data.filter((item) => {
        const includes =
          (item.name && item.name.includes(value)) ||
          (item.address && item.address.includes(value)) ||
          (item.role && item.role.includes(value)) ||
          (item.account && item.account.includes(value)) ||
          ''
        return includes
      })
      setFilteredData(updatedData)
      setSearchValue(value)
    }
  }

  // ** Function to handle Pagination
  const handlePagination = (page) => {
    setCurrentPage(page.selected)
  }

  // ** Custom Pagination
  const CustomPagination = () => (
    <ReactPaginate
      previousLabel=""
      nextLabel=""
      forcePage={currentPage}
      onPageChange={(page) => handlePagination(page)}
      pageCount={
        searchValue.length
          ? Math.ceil(filteredData.length / 7)
          : Math.ceil(data.length / 7) || 1
      }
      breakLabel="..."
      pageRangeDisplayed={2}
      marginPagesDisplayed={2}
      activeClassName="active"
      pageClassName="page-item"
      breakClassName="page-item"
      nextLinkClassName="page-link"
      pageLinkClassName="page-link"
      breakLinkClassName="page-link"
      previousLinkClassName="page-link"
      nextClassName="page-item next-item"
      previousClassName="page-item prev-item"
      containerClassName="pagination react-paginate separated-pagination pagination-sm justify-content-end pe-1 mt-1"
    />
  )

  // ** Converts table to CSV
  function convertArrayOfObjectsToCSV(array) {
    let result

    const columnDelimiter = ','
    const lineDelimiter = '\n'
    const keys = Object.keys(data[0])

    result = ''
    result += keys.join(columnDelimiter)
    result += lineDelimiter

    array.forEach((item) => {
      let ctr = 0
      keys.forEach((key) => {
        if (ctr > 0) result += columnDelimiter

        result += item[key]

        ctr++
      })
      result += lineDelimiter
    })

    return result
  }

  // ** Downloads CSV
  function downloadCSV(array) {
    const link = document.createElement('a')
    let csv = convertArrayOfObjectsToCSV(array)
    if (csv === null) return

    const filename = 'export.csv'

    if (!csv.match(/^data:text\/csv/i)) {
      csv = `data:text/csv;charset=utf-8,${csv}`
    }

    link.setAttribute('href', encodeURI(csv))
    link.setAttribute('download', filename)
    link.click()
  }

  return (
    <Fragment>
      <Card>
        <CardHeader className="flex-md-row flex-column align-md-items-center align-items-start border-bottom">
          <CardTitle tag="h4">在线用户列表</CardTitle>
          <div className="d-flex mt-md-0 mt-1">
            <User size={15} />
            <span className="align-middle ms-50">在线用户数：120人</span>
          </div>
        </CardHeader>
        <Row className="mx-0 mb-50">
          <Col className="d-flex align-items-center  mt-1" md="10" sm="12">
            <Input
              className="dataTable-filter"
              type="text"
              id="search-input"
              placeholder="输入用户名/账号"
              value={searchValue}
              onChange={handleFilter}
              style={{ width: '40%', marginRight: '20px' }}
            />
            <Button className="ms-2" color="primary">
              <span className="align-middle ms-50">搜索</span>
            </Button>
          </Col>
        </Row>
        <div className="react-dataTable react-dataTable-selectable-rows">
          <DataTable
            noHeader
            pagination
            columns={columns}
            paginationPerPage={7}
            className="react-dataTable"
            sortIcon={<ChevronDown size={10} />}
            paginationComponent={CustomPagination}
            paginationDefaultPage={currentPage + 1}
            selectableRowsComponent={BootstrapCheckbox}
            data={searchValue.length ? filteredData : data}
          />
        </div>
      </Card>

      <Modal
        isOpen={modalShow}
        toggle={handleModalShow}
        className="modal-dialog-centered"
      >
        <ModalHeader toggle={handleModalShow}>创建账号</ModalHeader>
        <ModalBody>
          <Row>
            <Col className="mb-1" xl="12" md="12" sm="12">
              <Label className="form-label" for="name" size="sm">
                用户名
              </Label>
              <Input type="text" id="name" placeholder="请输入" bsSize="sm" />
            </Col>
          </Row>
          <Row>
            <Col className="mb-1" xl="12" md="12" sm="12">
              <Label className="form-label" for="name" size="sm">
                账号
              </Label>
              <Input type="text" id="name" placeholder="请输入" bsSize="sm" />
            </Col>
          </Row>
          <Row>
            <Col className="mb-1" sm="12">
              <Label for="grade">所属角色</Label>
              <Select
                className="react-select mb-50"
                classNamePrefix="select"
                defaultValue={mockOptions[0]}
                options={mockOptions}
                isClearable={false}
              />
            </Col>
          </Row>
          <Row>
            <Col className="mb-1" xl="12" md="12" sm="12">
              <Label className="form-label" for="name" size="sm">
                密码
              </Label>
              <Input type="text" id="name" placeholder="请输入" bsSize="sm" />
            </Col>
          </Row>
        </ModalBody>
        <ModalFooter>
          <Button color="primary" onClick={handleModalShow} outline>
            取消
          </Button>
          <Button color="primary" onClick={handleModalShow}>
            确定
          </Button>
        </ModalFooter>
      </Modal>
    </Fragment>
  )
}

export default DataTableWithButtons
